# coding=utf-8
import time
import random
from selenium import webdriver
from PIL import Image
from ShowapiRequest import ShowapiRequest

driver = webdriver.Chrome()


# 浏览器初始化
def driver_init():
    driver.get("http://www.5itest.cn/register")
    driver.maximize_window()
    time.sleep(5)


def get_element(id):
    element = driver.find_element_by_id(id)
    return element


def get_range_user():
    user_info = ''.join(random.sample("1234567890abcdefg", 8))
    return user_info


# 获取图片信息
def get_code_image(file_name):
    # 将网页以png格式的图片保存
    driver.save_screenshot(file_name)
    # 获取到验证码的图片元素id
    code_element = driver.find_element_by_id("getcode_num")
    # 用location方法获取x和y的值
    print(code_element.location)
    left = code_element.location['x']
    top = code_element.location['y']
    # 用size方法获取width和height的值加上前面获取的坐标值可以计算出剩下两个点的值
    width = code_element.size['width'] + left
    height = code_element.size['height'] + top
    # 使用open方法打开前面保存的moke.png之后跟据坐标用crop方法获得图片位置后使用save方法保存
    im = Image.open(file_name)
    img = im.crop((left, top, width, height))
    img.save(file_name)


# 解析图片
def code_online(file_name):
    r = ShowapiRequest("http://route.showapi.com/184-4", "101290", "bff0fe2ab4a743538879d2f187ace8f1")
    r.addFilePara("image", file_name)
    r.addBodyPara("typeId", "35")
    r.addBodyPara("convert_to_jpg", "0")
    r.addBodyPara("needMorePrecise", "0")
    res = r.post()
    text = res.json()['showapi_res_body']['Result']

    return text


def run_main():
    driver_init()
    user_name_info = get_range_user()
    user_email = user_name_info + "@163.com"
    file_name = "D:/heqq/seleniumPython/image/test01.png"
    get_element("register_email").send_keys(user_email)
    get_element("register_nickname").send_keys(user_name_info)
    get_element("register_password").send_keys("111111")
    get_code_image(file_name)
    text = code_online(file_name)
    get_element("captcha_code").send_keys(text)
    get_element("register-btn").click()

    time.sleep(10)
    driver.close()


run_main()
